package cn.openea.perpartner.link.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.openea.perpartner.common.auth.config.AuthConfig;
import cn.openea.perpartner.common.auth.entity.LoginBody;
import cn.openea.perpartner.link.constant.CommonConstants;
import cn.openea.perpartner.link.util.CommonContextHolder;
import cn.openea.perpartner.link.util.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Weird077
 * @description TODO
 * @date 2022-12-01 19:06
 */
@Slf4j
@Component
public class ComponentPermissionInterceptor implements HandlerInterceptor {
    @Value("${link.header.sysid}")
    private String sysId;
    @Value("${link.header.syspwd}")
    private String sysPwd;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        Boolean is_interception = (Boolean) CommonContextHolder.getObject(CommonConstants.IS_INTERCEPTION);
        if (is_interception != null && is_interception) {
            return true;
        }
        LoginBody loginUser = (LoginBody) request.getAttribute(AuthConfig.SSO_USER);
        if (BeanUtil.isEmpty(loginUser)) {
            UserContext.clear();
            if (StrUtil.isBlank(request.getHeader("sysid")) || StrUtil.isBlank(request.getHeader("syspwd"))) {
                response.getWriter().println("{\"code\":\"201\", \"msg\":\"sysid or syspwd are not allowed to be empty!\"}");
                return false;
            }
            String valid = request.getHeader("sysid").concat(request.getHeader("syspwd"));
            if (!valid.equals(sysId.concat(sysPwd))) {
                response.getWriter().println("{\"code\":\"201\", \"msg\":\"sysid and syspwd validate failed!\"}");
                return false;
            }
        } else {
            UserContext.setLoginUser(loginUser);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           @Nullable ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                @Nullable Exception ex) throws Exception {
        UserContext.clear();
    }
}
